/**
 * @author zyj
 * @date 2022年06月09日 15:53
 * 两个线程轮流打印1-100的数字。
 */
public class 两个线程轮流打印1_100的数字 {
    public static void main(String[] args) {
        MyRunnable myRunnable= new MyRunnable();

        new Thread(myRunnable,"A").start();
        new Thread(myRunnable,"B").start();
    }
}

class MyRunnable implements Runnable{
    private int num = 1;
    @Override
    public void run() {
        while (true) {
            synchronized (this) {
                if (num <= 100) {
                    System.out.println(Thread.currentThread().getName() + " " + num);
                    num++;
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    notifyAll();
                    try {
                        wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }else {
                    break;
                }
            }
        }
    }
}
